package com.wannengbang.cloudleader.a_main;

import android.Manifest;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.google.gson.Gson;
import com.wannengbang.cloudleader.MyApplication;
import com.wannengbang.cloudleader.R;
import com.wannengbang.cloudleader.base.BaseActivity;
import com.wannengbang.cloudleader.base.DataCallBack;
import com.wannengbang.cloudleader.bean.BaseResponseBean;
import com.wannengbang.cloudleader.bean.ExchangeListBean;
import com.wannengbang.cloudleader.bean.FirmMsgBean;
import com.wannengbang.cloudleader.bean.OrderListBean;
import com.wannengbang.cloudleader.bean.UserInfoBean;
import com.wannengbang.cloudleader.bean.VersionBean;
import com.wannengbang.cloudleader.dialog.AllotAgentDialog;
import com.wannengbang.cloudleader.dialog.ShowRedEnvelopesDialog;
import com.wannengbang.cloudleader.event.ReLoginEvent;
import com.wannengbang.cloudleader.homepage.ExchangeMyListActivity;
import com.wannengbang.cloudleader.homepage.HomePageFragment;
import com.wannengbang.cloudleader.homepage.model.HomePageModelImpl;
import com.wannengbang.cloudleader.homepage.model.IHomePageModel;
import com.wannengbang.cloudleader.invite.InviteFragment;
import com.wannengbang.cloudleader.login.LoginActivity;
import com.wannengbang.cloudleader.mine.MineFragment;
import com.wannengbang.cloudleader.mine.MyOrderListActivity;
import com.wannengbang.cloudleader.mine.model.MineModelImpl;
import com.wannengbang.cloudleader.performance.PerformanceFragment;
import com.wannengbang.cloudleader.shop.ShopFragment;
import com.wannengbang.cloudleader.utils.PermissionsManager;
import com.wannengbang.cloudleader.utils.SPManager;
import com.wannengbang.cloudleader.utils.ToastUtil;
import com.wannengbang.cloudleader.utils.VersionUtil;
import com.wannengbang.cloudleader.widget.CommonDialog;
import com.wannengbang.cloudleader.widget.CommonNoTitleDialog;

import org.greenrobot.eventbus.Subscribe;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends BaseActivity {

    @BindView(R.id.fragment_container)
    FrameLayout fragmentContainer;
    @BindView(R.id.iv_home_icon)
    ImageView ivHomeIcon;
    @BindView(R.id.tv_home)
    TextView tvHome;
    @BindView(R.id.ll_home_page)
    LinearLayout llHomePage;
    @BindView(R.id.iv_performance_icon)
    ImageView ivPerformanceIcon;
    @BindView(R.id.tv_performance)
    TextView tvPerformance;
    @BindView(R.id.ll_performance)
    LinearLayout llPerformance;
    @BindView(R.id.iv_invite_icon)
    ImageView ivInviteIcon;
    @BindView(R.id.tv_invite)
    TextView tvInvite;
    @BindView(R.id.ll_invite)
    LinearLayout llInvite;
    @BindView(R.id.iv_mine_icon)
    ImageView ivMineIcon;
    @BindView(R.id.tv_mine)
    TextView tvMine;
    @BindView(R.id.ll_mine)
    LinearLayout llMine;

    public static final String fragmentTag_home = "home";
    public static final String fragmentTag_performance = "performance";
    public static final String fragmentTag_shop = "shop";
    public static final String fragmentTag_invite = "invite";
    public static final String fragmentTag_mine = "mine";
    public static final String MAIN_TAB = "main_tab";
    @BindView(R.id.iv_shop_icon)
    ImageView ivShopIcon;
    @BindView(R.id.tv_shop)
    TextView tvShop;
    @BindView(R.id.ll_shop)
    LinearLayout llShop;
    @BindView(R.id.main_rootView)
    LinearLayout mainRootView;

    private HomePageFragment homePageFragment;
    private PerformanceFragment performanceFragment;
    private ShopFragment shopFragment;
    private InviteFragment inviteFragment;
    private MineFragment mineFragment;

    private PermissionsManager permissionsManager;
    private String[] permissions;
    private CommonNoTitleDialog.Builder dialogBuild;
    private CommonDialog.Builder dialogFirmMsg;
    private CommonDialog.Builder dialogBuildTitle;
    private MineModelImpl mineModel;
    private IHomePageModel homePageModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        registerEventBus();
        initView();
        getPermissions();
        requestClientVersion();
        requestFirmMsg();
        requestMyOrderData();
        showRedEnvelopesDialog();
    }

    private void showRedEnvelopesDialog() {
        ShowRedEnvelopesDialog dialog = ShowRedEnvelopesDialog.newInstance();
        dialog.show(getSupportFragmentManager(), "dialog");
        dialog.setOnCallBackListener(() -> {
        });
    }

    private void initView() {
        mineModel = new MineModelImpl();
        homePageModel = new HomePageModelImpl();
        handlerFragmentShowHide(fragmentTag_home);

//        SystemConfigBean configBean = new Gson().fromJson(SPManager.getInstance().getSystemConfig(), SystemConfigBean.class);
//        if (configBean != null && configBean.getData() != null) {
//            if (configBean.getData().getClient_menu_visible().isIntegral_shop()) {
//                llShop.setVisibility(View.VISIBLE);
//            } else {
//                llShop.setVisibility(View.GONE);
//            }
//        }
    }

    /**
     * 版本更新
     */
    private void requestClientVersion() {
        homePageModel.requestClientVersion(new DataCallBack<VersionBean>() {
            @Override
            public void onSuccessful(VersionBean bean) {
                String versionName = bean.getData().getVersion().replace(".", "");
                int versionCode = 0;
                if (!TextUtils.isEmpty(versionName)) {
                    versionCode = Integer.parseInt(versionName);
                }
                if (versionCode > VersionUtil.packageCode(mActivity)) {
                    if (bean.getData().getForce_update() == 1) {
                        dialogBuild = new CommonNoTitleDialog.Builder(mActivity);
                        dialogBuild.setMessage("发现新版本，请升级");
                        dialogBuild.setPositiveVersionButton("去升级", v -> {
                            goToMarket(mActivity, getPackageName());
                        });
                        dialogBuild.setCancelable(false);
                        dialogBuild.show();
                        dialogBuild.setNegativeButtonGONE();
                    } else {
                        dialogBuild = new CommonNoTitleDialog.Builder(mActivity);
                        dialogBuild.setMessage("发现新版本，请升级");
                        dialogBuild.setPositiveVersionButton("去升级", v -> {
                            dialogBuild.dismiss();
                            dialogBuild = null;
                            goToMarket(mActivity, getPackageName());
                        });
                        dialogBuild.setNegativeButton("取消", v -> {
                            dialogBuild.dismiss();
                            dialogBuild = null;
                        });
                        dialogBuild.setCancelable(false);
                        dialogBuild.show();
                    }
                }
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    /**
     * 弹框消息
     */
    public void requestFirmMsg() {
        homePageModel.requestFirmMsg(new DataCallBack<FirmMsgBean>() {
            @Override
            public void onSuccessful(FirmMsgBean bean) {
                if (bean.getData() != null) {
                    dialogFirmMsg = new CommonDialog.Builder(mActivity);
                    dialogFirmMsg.setTitle(bean.getData().getTitle());
                    dialogFirmMsg.setMessage(bean.getData().getContent());
                    dialogFirmMsg.setPositiveButton("我知道了", v -> {
                        requestEditFrameStatus(bean.getData().getId() + "");
                        dialogFirmMsg.dismiss();
                        dialogFirmMsg = null;
                    });
                    dialogFirmMsg.setNegativeButton("取消", v -> {
                        dialogFirmMsg.dismiss();
                        dialogFirmMsg = null;
                    });
                    dialogFirmMsg.setCancelable(false);
                    dialogFirmMsg.show();
                }
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    /**
     * 弹框消息 已读
     */
    public void requestEditFrameStatus(String id) {
        homePageModel.requestEditFrameStatus(id, new DataCallBack<BaseResponseBean>() {
            @Override
            public void onSuccessful(BaseResponseBean bean) {

            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    /**
     * 采购的机具  待收货提醒
     */
    public void requestMyOrderData() {
        mineModel.requestMyOrderData(1, "order_by_me", "3", new DataCallBack<OrderListBean>() {
            @Override
            public void onSuccessful(OrderListBean bean) {
                if (bean.getData().getItemList() != null && bean.getData().getItemList().size() > 0) {
                    dialogBuildTitle = new CommonDialog.Builder(mActivity);
                    dialogBuildTitle.setTitle("提示");
                    dialogBuildTitle.setMessage("您有待收货的订单，请及时确认收货");
                    dialogBuildTitle.setPositiveButton("去收货", v -> {
                        dialogBuildTitle.dismiss();
                        Intent intent = new Intent(mActivity, MyOrderListActivity.class);
                        intent.putExtra("selectPosition", 3);
                        startActivity(intent);
                        dialogBuildTitle = null;
                    });
                    dialogBuildTitle.setNegativeButton("取消", v -> {
                        dialogBuildTitle.dismiss();
                        dialogBuildTitle = null;
                    });
                    dialogBuildTitle.setCancelable(false);
                    dialogBuildTitle.show();
                } else {
                    requestExchangeData();
                }
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    /**
     * 兑换的机具 待收货提醒
     */
    public void requestExchangeData() {
        UserInfoBean userInfoBean = new Gson().fromJson(SPManager.getInstance().getUserInfoJson(), UserInfoBean.class);
        if (userInfoBean != null && userInfoBean.getData().getId() != 1) {
            mineModel.requestAgentExchangeDeviceIndex(1, "1", "2", new DataCallBack<ExchangeListBean>() {
                @Override
                public void onSuccessful(ExchangeListBean bean) {
                    if (bean.getData().getItemList() != null && bean.getData().getItemList().size() > 0) {
                        dialogBuildTitle = new CommonDialog.Builder(mActivity);
                        dialogBuildTitle.setTitle("提示");
                        dialogBuildTitle.setMessage("您有待收货的订单，请及时确认收货");
                        dialogBuildTitle.setPositiveButton("去收货", v -> {
                            dialogBuildTitle.dismiss();
                            Intent intent = new Intent(mActivity, ExchangeMyListActivity.class);
                            intent.putExtra("selectPosition", 2);
                            startActivity(intent);
                            dialogBuildTitle = null;
                        });
                        dialogBuildTitle.setNegativeButton("取消", v -> {
                            dialogBuildTitle.dismiss();
                            dialogBuildTitle = null;
                        });
                        dialogBuildTitle.setCancelable(false);
                        dialogBuildTitle.show();
                    }
                }

                @Override
                public void onFailed(String msg, String code) {

                }
            });
        }
    }

    /**
     * @param context
     * @param packageName
     */
    public static void goToMarket(Context context, String packageName) {
        try {
            Uri uri = Uri.parse("market://details?id=" + packageName);
            Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
            goToMarket.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(goToMarket);
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
            Toast.makeText(context, "您的手机没有安装Android应用市场", Toast.LENGTH_SHORT).show();
        }
    }

    @Subscribe
    public void ReLoginEvent(ReLoginEvent event) {
        if (dialogBuild == null) {
            SPManager.getInstance().logOffRemove();
            Intent intent = new Intent(MyApplication.getApplication(), MainActivity.class);
            intent.putExtra(MainActivity.MAIN_TAB, MainActivity.fragmentTag_home);
            startActivity(intent);
            dialogBuild = new CommonNoTitleDialog.Builder(this);
            dialogBuild.setMessage("登录已过期，是否重新登录");
            dialogBuild.setPositiveButton("登录", v -> {
                dialogBuild.dismiss();
                startActivity(new Intent(mActivity, LoginActivity.class));
                dialogBuild = null;
            });
            dialogBuild.setNegativeButton("否", v -> {
                dialogBuild.dismiss();
                dialogBuild = null;
            });
            dialogBuild.setCancelable(false);
            dialogBuild.show();
        }
    }

    /**
     * 获取权限
     */
    public void getPermissions() {
        permissions = new String[]{
                Manifest.permission.WRITE_EXTERNAL_STORAGE,//
                Manifest.permission.READ_EXTERNAL_STORAGE, //
                Manifest.permission.READ_PHONE_STATE};

        if (PermissionsManager.checkPermissions(permissions)) {

            return;
        }
        permissionsManager = new PermissionsManager(this);
        permissionsManager.setResultListener((allGranted, rejectPermissionList) -> {
            if (allGranted) {

            } else {
                permissionsManager.showDialog();
            }

        });

        permissionsManager.requestPermissionsEach(permissions);

    }

    @Override
    public void handlerPermissionForActivityResult() {
        if (PermissionsManager.checkPermissions(permissions)) {

        }
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        String mTab = intent.getStringExtra(MAIN_TAB);

        if (fragmentTag_home.equals(mTab)) {
            llHomePage.performClick();
        } else if (fragmentTag_performance.equals(mTab)) {
            llPerformance.performClick();
        } else if (fragmentTag_shop.equals(mTab)) {
            llShop.performClick();
        } else if (fragmentTag_invite.equals(mTab)) {
            llInvite.performClick();
        } else if (fragmentTag_mine.equals(mTab)) {
            llMine.performClick();
        }
    }

    @Override
    public void onAttachFragment(Fragment fragment) {
        if (homePageFragment == null && fragment instanceof HomePageFragment)
            homePageFragment = (HomePageFragment) fragment;
        if (performanceFragment == null && fragment instanceof PerformanceFragment)
            performanceFragment = (PerformanceFragment) fragment;
        if (shopFragment == null && fragment instanceof ShopFragment)
            shopFragment = (ShopFragment) fragment;
        if (inviteFragment == null && fragment instanceof InviteFragment)
            inviteFragment = (InviteFragment) fragment;
        if (mineFragment == null && fragment instanceof MineFragment)
            mineFragment = (MineFragment) fragment;
    }

    // 当fragment已被实例化，相当于发生过切换，就隐藏起来
    public void hideFragments(FragmentTransaction ft) {
        if (homePageFragment != null)
            ft.hide(homePageFragment);
        if (performanceFragment != null)
            ft.hide(performanceFragment);
        if (shopFragment != null)
            ft.hide(shopFragment);
        if (inviteFragment != null)
            ft.hide(inviteFragment);
        if (mineFragment != null)
            ft.hide(mineFragment);
    }

    /**
     * fragment 的显示和隐藏
     */
    private void handlerFragmentShowHide(String tag) {
        FragmentTransaction ft2 = getSupportFragmentManager().beginTransaction();
        hideFragments(ft2);
        switch (tag) {
            case fragmentTag_home:
                if (homePageFragment != null)
                    ft2.show(homePageFragment);
                else {
                    homePageFragment = new HomePageFragment();
                    ft2.add(R.id.fragment_container, homePageFragment);
                }
                break;
            case fragmentTag_performance:
                if (performanceFragment != null)
                    ft2.show(performanceFragment);
                else {
                    performanceFragment = new PerformanceFragment();
                    ft2.add(R.id.fragment_container, performanceFragment);
                }
                break;
            case fragmentTag_shop:
                if (shopFragment != null)
                    ft2.show(shopFragment);
                else {
                    shopFragment = new ShopFragment();
                    ft2.add(R.id.fragment_container, shopFragment);
                }
                break;
            case fragmentTag_invite:
                if (inviteFragment != null)
                    ft2.show(inviteFragment);
                else {
                    inviteFragment = new InviteFragment();
                    ft2.add(R.id.fragment_container, inviteFragment);
                }
                break;
            case fragmentTag_mine:
                if (mineFragment != null)
                    ft2.show(mineFragment);
                else {
                    mineFragment = new MineFragment();
                    ft2.add(R.id.fragment_container, mineFragment);
                }
                break;
        }
        ft2.commitAllowingStateLoss();
        getSupportFragmentManager().executePendingTransactions();
    }

    /**
     * 设置默认图标
     */
    private void setAllIconNormal() {

        int textColor = getResources().getColor(R.color.text_color_7);
        tvHome.setTextColor(textColor);
        tvPerformance.setTextColor(textColor);
        tvShop.setTextColor(textColor);
        tvInvite.setTextColor(textColor);
        tvMine.setTextColor(textColor);

        ivHomeIcon.setImageResource(R.mipmap.ic_home_unchecked);
        ivPerformanceIcon.setImageResource(R.mipmap.ic_performance_unchecked);
        ivShopIcon.setImageResource(R.mipmap.ic_shop_unchecked);
        ivInviteIcon.setImageResource(R.mipmap.ic_invite_unchecked);
        ivMineIcon.setImageResource(R.mipmap.ic_me_uncheck);

    }

    @OnClick({R.id.ll_home_page, R.id.ll_performance, R.id.ll_shop, R.id.ll_invite, R.id.ll_mine})
    public void onViewClicked(View view) {
        int color_checked = getResources().getColor(R.color.theme_color);
        switch (view.getId()) {
            case R.id.ll_home_page:
                setAllIconNormal();
                tvHome.setTextColor(color_checked);
                ivHomeIcon.setImageResource(R.mipmap.ic_home_checked);
                handlerFragmentShowHide(fragmentTag_home);
                break;
            case R.id.ll_performance:
                setAllIconNormal();
                tvPerformance.setTextColor(color_checked);
                ivPerformanceIcon.setImageResource(R.mipmap.ic_performance_checked);
                handlerFragmentShowHide(fragmentTag_performance);
                break;
            case R.id.ll_shop:
                setAllIconNormal();
                tvShop.setTextColor(color_checked);
                ivShopIcon.setImageResource(R.mipmap.ic_shop_checked);
                handlerFragmentShowHide(fragmentTag_shop);
                break;
            case R.id.ll_invite:
                setAllIconNormal();
                tvInvite.setTextColor(color_checked);
                ivInviteIcon.setImageResource(R.mipmap.ic_invite_checked);
                handlerFragmentShowHide(fragmentTag_invite);
                break;
            case R.id.ll_mine:
                setAllIconNormal();
                tvMine.setTextColor(color_checked);
                ivMineIcon.setImageResource(R.mipmap.ic_me_checked);
                handlerFragmentShowHide(fragmentTag_mine);
                break;
        }
    }

    private long clickKeyBackTime = 0;


    /**
     * 返回桌面不推出程序
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {

            long timeMillis = System.currentTimeMillis();
            if (timeMillis - clickKeyBackTime < 2000) {
                Intent intent = new Intent(Intent.ACTION_MAIN);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.addCategory(Intent.CATEGORY_HOME);
                startActivity(intent);
            } else {
                ToastUtil.showShort("再点一次退出");
                clickKeyBackTime = timeMillis;
            }
        }
        return false;
    }
}
